package com.ics.cmsadmin.modules.basic.service.impl;

import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.enums.OrderStatusEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.frame.utils.KeyUtil;
import com.ics.cmsadmin.modules.agent.bean.AgentInfoBean;
import com.ics.cmsadmin.modules.agent.service.AgentInfoService;
import com.ics.cmsadmin.modules.basic.bean.OrderBean;
import com.ics.cmsadmin.modules.basic.bean.StudentBean;
import com.ics.cmsadmin.modules.basic.dao.StudentDao;
import com.ics.cmsadmin.modules.basic.service.OrderService;
import com.ics.cmsadmin.modules.basic.service.StudentOrderService;
import com.ics.cmsadmin.modules.basic.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * t_student
 * Created bylvsw on 2018-54-22 19:09:15.
 */
@Service("newStudentService")
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentDao studentDao;
    @Resource
    private AgentInfoService agentInfoService;
    @Resource
    private StudentOrderService studentOrderService;
    @Resource
    private OrderService orderService;

    @Override
    public StudentBean queryById(String id) {
        if (StringUtils.isBlank(id)){
            return null;
        }
        return studentDao.queryById(id);
    }

    @Override
    public PageResult list(StudentBean bean, PageBean page) {
        long count = studentDao.count(bean);
        if (count == 0){
            return new PageResult();
        }
        page = page == null ? new PageBean() : page;
        return PageResult.getPage(count, studentDao.list(bean, page));
    }

    @Override
    public PageResult listByLoginUserId(StudentBean bean, String loginUserId, PageBean page) {
        return listByLoginUserId(bean, loginUserId, page, studentDao);
    }

    @Override
    public boolean insert(StudentBean bean) {
        if (bean == null){
            return false;
        }
        bean.setId(KeyUtil.genUniqueKey());
        AgentInfoBean agentInfoBean = agentInfoService.queryById(bean.getAgentNo());
        if (agentInfoBean == null){
            bean.setAgentNo("0");
        }else{
            bean.setSalesman(agentInfoBean.getSalesman());
        }
        return studentDao.insert(bean) == 1;
    }

    @Override
    public boolean update(String id, StudentBean bean) {
        if (StringUtils.isBlank(id) || bean == null || queryById(id) == null){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "参数有误");
        }
        return studentDao.update(id, bean) == 1;
    }

    @Override
    public Object updateVip(String id, StudentBean bean) {
        if (StringUtils.isBlank(id) || bean == null || queryById(id) == null){
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "参数有误");
        }
        PageResult pageOrder =  orderService.list(OrderBean.builder().userId(bean.getId()).build(),new PageBean(OrderStatusEnum.WAIT.getCode(),Integer.MAX_VALUE));
        List<OrderBean> orderList = pageOrder.getDataList();
        if (orderList!=null && !orderList.isEmpty()){
            if (!bean.getSpecialVip()){
                ArrayList<String> removeOrderIds = new ArrayList<>();
                for (OrderBean order: orderList) {
                    if (!(order.getOrderAmount().compareTo(BigDecimal.ONE)==1)){
                        removeOrderIds.add(order.getId());
                    }
                }
                if (removeOrderIds.size()>0){
                    orderService.batchSoftRemove(removeOrderIds);
                }
            }else{
                ArrayList<String> removeOrderIds = new ArrayList<>();
                for (OrderBean order: orderList) {
                    if (order.getStatus()!=2){
                        removeOrderIds.add(order.getId());
                    }
                }
                if (removeOrderIds.size()>0){
                    orderService.batchSoftRemove(removeOrderIds);
                }
            }
        }
        return studentDao.update(id, bean) == 1;
    }

    @Override
    public boolean delete(String id) {
        if (StringUtils.isBlank(id) || queryById(id) == null){
            throw new CmsException(ApiResultEnum.DELETE_TABLE_ITEM_FAIL, "参数有误");
        }
        return studentDao.delete(id) == 1;
    }

    @Override
    public StudentBean refreshStudentInfoByWechat(StudentBean student) {
        if (student == null || StringUtils.isBlank(student.getOpenId())){
            return null;
        }
        StudentBean existStudent = null;
        if (StringUtils.isNotBlank(student.getUnionId())) {
            existStudent = studentDao.findOne(StudentBean.builder()
                .unionId(student.getUnionId())
                .build());
        }
        if (existStudent == null) {
            existStudent = studentDao.findOne(StudentBean.builder()
                .openId(student.getOpenId())
                .registerSource(student.getRegisterSource())
                .build());
        }
        if(existStudent == null){
            insert(student);
            return student;
        }else {
            update(existStudent.getId(), student);
            return queryById(existStudent.getId());
        }
    }

}
